package com.emuporium.gymrat.server.exercise;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.emuporium.gymrat.server.data.ExerciseDB;
import com.emuporium.gymrat.server.data.User;
import com.emuporium.gymrat.server.data.UserDB;

@SuppressWarnings("serial")
public class ExerciseCreateSubmitServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		int musclegroup = new Integer(request.getParameter("musclegroup"));
		String name = request.getParameter("name");
		String[] variationsString = request
				.getParameterValues("variationCheck");
		String[] equipmentString = request.getParameterValues("equipmentCheck");
		ArrayList<Integer> variations = new ArrayList<Integer>();
		ArrayList<Integer> equipment = new ArrayList<Integer>();
		int userId = 0;
		
		User user = UserDB.selectUser(request.getRemoteUser());
		
		if(user != null)
			userId = user.getId();
		
		if (request.getParameter("publicexercise") != null)
			userId = 0;

		if (variationsString != null)
			for (String s : variationsString) {
				variations.add(new Integer(s));
			}

		if (equipmentString != null)
			for (String s : equipmentString) {
				equipment.add(new Integer(s));
			}

		ExerciseDB.insertExercise(name, musclegroup, variations, equipment,
				userId);

		request.setAttribute("redirecturl", "/exercise/list");
		String url = "/includes/redirect.jsp";
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);

	}

}
